package cn.livingCloud.service.impl.operation;

import cn.livingCloud.context.BeanProvider;
import cn.livingCloud.dto.UserAccountFormDto;
import cn.livingCloud.entity.user.AccountPrivilege;
import cn.livingCloud.entity.user.Privilege;
import cn.livingCloud.entity.user.User;
import cn.livingCloud.entity.user.UserAccount;
import cn.livingCloud.repository.AccountPrivilegeMapper;
import cn.livingCloud.repository.UserAccountMapper;
import cn.livingCloud.repository.UserMapper;
import org.springframework.util.StringUtils;

import java.util.List;

/**
 * Created by sujiantang on 2015/12/7.
 */
public class UserAccountFormDtoUpdater {
    private transient UserAccountMapper mapper = BeanProvider.getBean(UserAccountMapper.class);
    private transient UserMapper userMapper = BeanProvider.getBean(UserMapper.class);
    private transient AccountPrivilegeMapper accountPrivilegeMapper = BeanProvider.getBean(AccountPrivilegeMapper.class);

    private UserAccountFormDto formDto;

    public UserAccountFormDtoUpdater(UserAccountFormDto formDto) {
        this.formDto = formDto;
    }

    public String update() {
        User user = userMapper.findUserByUuid(formDto.getUserId());
        if (StringUtils.isEmpty(formDto.getUuid())) {
            createUserAccount(user);
        } else {
            updateUserAccount();
        }
        return user.getUuid();
    }

    private void updateUserAccount() {
        UserAccount userAccount = mapper.findUserAccountByUuid(formDto.getUuid());
        accountPrivilegeMapper.deleteAccountPrivilege(userAccount.getUuid());
        userAccount.getPrivilegeList().clear();
        updatePrivilege(userAccount);
    }

    private void updatePrivilege(UserAccount userAccount) {
        AccountPrivilege accountPrivilege;
        List<AccountPrivilege> privilegeList = userAccount.getPrivilegeList();
        for (Privilege privilege : formDto.getPrivilegeList()) {
            accountPrivilege = new AccountPrivilege()
                    .setUserAccountId(userAccount.getUuid())
                    .setPrivilege(privilege);
            privilegeList.add(accountPrivilege);
        }
        accountPrivilegeMapper.insertList(privilegeList);
    }

    private void createUserAccount(User user) {
        UserAccount userAccount = new UserAccount();
        formDto.updateAccount(userAccount);
        userAccount.setUserId(user.getUuid());
        userAccount.setUser(user);
        userAccount.save();

        updatePrivilege(userAccount);
    }
}
